package com.aitaoxue.palx.ui.register;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Paint;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.InjectView;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.AppManager;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseActivity;
import com.aitaoxue.palx.db.InfoDBHelper;
import com.aitaoxue.palx.ui.CityChooseAvtivity;
import com.aitaoxue.palx.ui.WebViewActivity;
import com.aitaoxue.palx.util.MD5Utils;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class RegisterActivity3 extends BaseActivity {

	@InjectView(R.id.real_name)
	EditText name;
	@InjectView(R.id.password)
	EditText password;
	@InjectView(R.id.re_password)
	EditText rePassword;
	@InjectView(R.id.web_content)
	TextView webContent;
	@InjectView(R.id.btn_push)
	Button push;
	@InjectView(R.id.check_male)
	ImageView checkMale;
	@InjectView(R.id.check_female)
	ImageView checkFemale;
	@InjectView(R.id.password_grade)
	ImageView passwordGrade;
	@InjectView(R.id.city_layout)
	RelativeLayout cityLayout;
	@InjectView(R.id.city)
	TextView city;
	@InjectView(R.id.web)
	ImageView web;
	@InjectView(R.id.alert_line)
	RelativeLayout alertLine;
	@InjectView(R.id.alert_content)
	TextView alertContent;

	private boolean isAgree = false;

	private enum SEX {
		male, female;
	}

	private SEX sex = SEX.male;

	private static final int CHOOSE_CITY_STATUS = 1;

	// 全数字或全字母或全特殊字符
	private Pattern p1;
	// 数字+字母
	private Pattern p2;
	// 数字+字母+特殊字符
	private Pattern p3;

	private TextWatcher watcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			String str = s.toString();
			int grade = judgePassword(str);
			switch (grade) {
			case -1:
				passwordGrade.setImageResource(R.drawable.progress0);
				break;
			case 0:
				passwordGrade.setImageResource(R.drawable.progress1);
				break;
			case 1:
				passwordGrade.setImageResource(R.drawable.progress2);
				break;
			case 2:
				passwordGrade.setImageResource(R.drawable.progress3);
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected boolean hasBackButton() {
		return true;
	}

	@Override
	protected int getActionBarTitle() {
		return R.string.register;
	}

	protected int getLayoutId() {
		return R.layout.activity_register_3;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.check_male:
			if (sex == SEX.male) {
			} else {
				checkMale.setImageResource(R.drawable.register_checked);
				checkFemale.setImageResource(R.drawable.register_not_checked);
				sex = SEX.male;
			}
			break;
		case R.id.check_female:
			if (sex == SEX.female) {
			} else {
				checkMale.setImageResource(R.drawable.register_not_checked);
				checkFemale.setImageResource(R.drawable.register_checked);
				sex = SEX.female;
			}
			break;
		case R.id.city_layout:
			startActivityForResult(new Intent(RegisterActivity3.this,
					CityChooseAvtivity.class), CHOOSE_CITY_STATUS);
			break;
		case R.id.web:
			if (isAgree) {
				web.setImageResource(R.drawable.register_not_agree);
			} else {
				web.setImageResource(R.drawable.register_agree);
			}
			isAgree = !isAgree;
			break;
		case R.id.web_content:
			Intent intent = new Intent(this, WebViewActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_push:
			if (checkIfReady()) {
				showWaitDialog();
				int id = InfoDBHelper.getCityId(city.getText().toString());
				AitaoXueApi.register(getIntent().getStringExtra("phone"),
						password.getText().toString(), rePassword.getText()
								.toString(), String.valueOf(id), name.getText()
								.toString(), sex == SEX.male ? "1" : "0",
						mHandler);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void initView() {
		webContent.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		webContent.getPaint().setAntiAlias(true);

		checkMale.setOnClickListener(this);
		checkFemale.setOnClickListener(this);
		cityLayout.setOnClickListener(this);
		web.setOnClickListener(this);
		webContent.setOnClickListener(this);
		push.setOnClickListener(this);

		password.addTextChangedListener(watcher);
		
		AppManager.getAppManager().addActivity(this);
	}

	@Override
	public void initData() {
		p1 = Pattern.compile("^(\\d+|[a-zA-Z]+|[!@#$%^&*_]+)$");
		p2 = Pattern.compile("^([a-zA-Z]|\\d)+$");
		p3 = Pattern.compile("^(\\d|[a-zA-Z]|[!@#$%^&*_])+$");
	}

	// 匹配密码 -1:0强度 0:弱 1:中 2:强
	private int judgePassword(String pwd) {
		int length = pwd.length();

		if (length < 6) {
			return -1;
		} else if (length >= 6 && length <= 8) {
			Matcher m1 = p1.matcher(pwd);
			if (m1.matches()) {
				return 0;
			}

			Matcher m2 = p2.matcher(pwd);
			if (m2.matches()) {
				return 1;
			}

			Matcher m3 = p3.matcher(pwd);
			if (m3.matches()) {
				return 1;
			}
		} else {
			Matcher m1 = p1.matcher(pwd);
			if (m1.matches()) {
				return 1;
			}

			Matcher m2 = p2.matcher(pwd);
			if (m2.matches()) {
				return 1;
			}

			Matcher m3 = p3.matcher(pwd);
			if (m3.matches()) {
				return 2;
			}
		}
		return -1;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CHOOSE_CITY_STATUS && resultCode == RESULT_OK) {
			// 获得城市成功
			if (data.getStringExtra("selected_city") != null) {
				// setCity(data.getStringExtra("selected_city"));
				city.setText(data.getStringExtra("selected_city"));
			}
		}
	}

	private boolean checkIfReady() {
		if (TextUtils.isEmpty(name.getText().toString())) {
			showError("请输入姓名");
			return false;
		}
		if (TextUtils.isEmpty(password.getText().toString())) {
			showError("请输入密码");
			return false;
		}
		if (TextUtils.isEmpty(rePassword.getText().toString())) {
			showError("请输入确认密码");
			return false;
		}
		if (!TextUtils.equals(password.getText().toString(), rePassword
				.getText().toString())) {
			showError("密码输入不一致");
			return false;
		}
		if (TextUtils.isEmpty(city.getText().toString())) {
			showError("请选择城市");
			return false;
		}
		if (!isAgree) {
			showError("请确认同意用户协议");
		}

		return true;
	}

	private void showError(String str) {
		if (alertLine.getVisibility() == View.GONE) {
			alertLine.setVisibility(View.VISIBLE);
		}
		alertContent.setText(str);
	}

	private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);

				String code = json.getString("code");
				if (code.equals("0000")) {
					// success
					// 将用户名和密码保存起来
					AppContext.getInstance().setProperty("user.username",
							getIntent().getStringExtra("phone"));
					AppContext.getInstance().setProperty("user.password",
							MD5Utils.md5(password.getText().toString()));
					Intent intent = new Intent(RegisterActivity3.this,
							RegisterActivity4.class);
					startActivity(intent);
					//finish();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}
	};

}
